import json
import pandas as pd
import os
import pickle


def export_data(tickets, products, output_dir="recommendation_data"):
    """导出所有数据到文件"""
    # 确保输出目录存在
    os.makedirs(output_dir, exist_ok=True)

    # 导出完整JSON
    export_full_recommendations(tickets, output_dir)

    # 导出推荐明细CSV
    export_recommendation_details(tickets, output_dir)

    # 导出用户偏好数据
    export_user_preferences(tickets, output_dir)

    # 导出商品数据
    export_product_catalog(products, output_dir)

    print("数据导出完成!")
    print(f"所有文件已保存到 {output_dir} 目录")


def export_full_recommendations(tickets, output_dir):
    """导出完整推荐工单到JSON文件"""
    filepath = os.path.join(output_dir, 'full_recommendations.json')
    with open(filepath, 'w', encoding='utf-8') as f:
        json.dump(tickets, f, ensure_ascii=False, indent=2)
    print(f"- 完整推荐工单: {filepath}")


def export_recommendation_details(tickets, output_dir):
    """导出推荐明细到CSV文件"""
    csv_data = []
    for ticket in tickets:
        for rec in ticket.get('recommendations', []):
            csv_data.append({
                "ticket_id": ticket["ticket_id"],
                "user_id": ticket["user_id"],
                "request_time": ticket["request_time"],
                "product_id": rec["product_id"],
                "product_name": rec["name"],
                "category": rec["category"],
                "price": rec["price"],
                "match_score": rec["match_score"],
                "user_cluster": ticket["ml_metadata"]["user_cluster"],
                "status": ticket["status"]
            })

    filepath = os.path.join(output_dir, 'recommendation_details.csv')
    pd.DataFrame(csv_data).to_csv(filepath, index=False)
    print(f"- 推荐明细: {filepath}")


def export_user_preferences(tickets, output_dir):
    """导出用户偏好数据到CSV文件"""
    user_prefs = []
    for ticket in tickets:
        user_prefs.append({
            "user_id": ticket["user_id"],
            "flavors": ",".join(ticket["preferences"]["flavor_profile"]),
            "categories": ",".join(ticket["preferences"]["category_pref"]),
            "health_constraints": ",".join(ticket["preferences"]["health_constraints"]),
            "price_range": ticket["preferences"]["price_range"]
        })

    filepath = os.path.join(output_dir, 'user_preferences.csv')
    pd.DataFrame(user_prefs).to_csv(filepath, index=False)
    print(f"- 用户偏好: {filepath}")


def export_product_catalog(products, output_dir):
    """导出商品目录到CSV文件"""
    filepath = os.path.join(output_dir, 'product_catalog.csv')
    product_df = pd.DataFrame(products)
    product_df.to_csv(filepath, index=False)
    print(f"- 商品目录: {filepath}")


def save_models(recommender, output_dir):
    """保存机器学习模型"""
    filepath = os.path.join(output_dir, 'models.pkl')
    recommender.save_models(filepath)
    print(f"- 机器学习模型: {filepath}")